package com.cj.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class BaseDao<T> {

    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    QueryRunner qr = new QueryRunner(dataSource);

    public T getEntity(String sql, Class clasz, Object ...obj){
        try {
            return qr.query(sql, new BeanHandler<T>(clasz), obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
        
    }


    public List<T> getEntities(String sql, Class clasz, Object ...obj){
        try {
            return qr.query(sql, new BeanListHandler<T>(clasz), obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int getTotalCount(String sql,Object ...obj)  {
        //        new ScalarHandler() 返回long型，不能直接转为 int  ，需要调用 intValue

        try {
           Number  count = (Number) qr.query(sql, new ScalarHandler<>(), obj);
            return count.intValue();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }


    public int update(String sql,Object ...obj){
        try {
            return qr.update(sql, obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }


}
